const fs = require('fs');
const { readJsonFile } = require('../utils');

const validator = {
  license(value, { license }) {
    if(value){
      return value  
    }
    return license
  },
  publishAs(value, { publishAs }) {
    if(value){
      return value  
    }
    return publishAs
  },
  dirs(value) {
    if (Array.isArray(value)){
      return {}
    }
    return value
  },
  envs(value) {
    if (Array.isArray(value)){
      return {}
    }
    return value
  },
  segment(value, { segment }) {
    if(Array.isArray(value)) {
      return segment
    }
    if (!Object.keys(value).includes("destPath")) {
      return segment
    }
    return value
  },
  version(value, { version }) {
    return version
  },
  description(value, { description }) {
    if(!value || value.startsWith("Third-party open-source")) {
      return description
    }
    return value
  },
  licensePath(value, { licensePath, require }) {
    if (require) {
      return licensePath
    }
    if(!value){
      return licensePath
    }
    return value
  },
  readmePath(value, { readmePath, require }) {
    if (require) {
      return readmePath
    }
    if (value && value.en) {
      return value
    }
    return readmePath
  }
}

class Bundle {
  constructor(bundleJsonDir, otherData) {
    this.json = readJsonFile(bundleJsonDir)
    this.otherData = otherData
    this.bundleJsonDir = bundleJsonDir
  }
  rewriteBundle() {
    for (const key in this.otherData) {
      const callBack = validator[key]
      if (callBack && typeof callBack === "function") {
        this.json[key] = callBack(this.json[key], this.otherData)
      }
    }
    return this
  }
  toJson() {
    return this.json
  }
  saveToFile() {
    const data = JSON.stringify(this.toJson(), null, 4)
    fs.writeFileSync(this.bundleJsonDir, data)
  }
}

module.exports = {
  Bundle
};
